package com.wali.common.ccp.execl;

import com.wali.common.ccp.exception.CcpException;
import com.wali.common.ccp.execl.annotation.CcpExcelField;
import com.wali.common.ccp.execl.common.CcpExcelReflections;
import com.wali.common.enums.ErrorCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author wali
 * @ClassName CcpExcelReport
 * @Description 导出execl文件, 导出“XLSX”格式
 * @email wali.xu@kpmg.com
 * @date 26/09/2018 11:00 上午
 */
public class CcpExcelReport {
    /**
     * 日志对象
     */
    private static Logger logger = LoggerFactory.getLogger(CcpExcelReport.class);

    /**
     * 工作薄对象
     */
    private HSSFWorkbook hssfWorkbook;

    /**
     * 工作表对象
     */
    private HSSFSheet hssfSheet;

    /**
     * 样式列表
     */
    private Map<String, CellStyle> stylesMap;

    /**
     * 是否使用模版（默认不使用模版）
     */
    private boolean templateUsed = false;

    /**
     * 模版文件路径
     */
    private String templateFilePath = null;

    /**
     * 实体注解Class对象
     */
    private Class<?> tempEntityClass = null;

    /**
     * 样式工作表号（仅对根据模版导出有效）
     */
    private int tempSheetNum = 0;

    /**
     * 样式模版行号（仅对根据模版导出有效）
     */
    private int tempStyleRownum = 1;

    /**
     * 首个插入数据的行号（仅对根据模版导出有效）
     */
    private int firstDataRownum = 2;

    /**
     * 是否删除模版行
     */
    private boolean tempRowRemoveRequired = true;

    /**
     * 当前行号
     */
    private int rownum;

    /**
     * 注解列表（Object[]{ ExcelField, Field/Method }）
     */
    private List<Object[]> annotationList = new ArrayList<Object[]>();

    /**
     * @param templateFilePath-- 模版文件路径
     * @throws CcpException--（读入模版文件异常或模版文件未找到）
     * @Title CcpExcelReport
     * @Description 根据模版导出数据
     */
    public CcpExcelReport(String templateFilePath)
            throws CcpException {
        // 设置模版文件路径
        this.templateFilePath = templateFilePath;

        // 根据模版文件进行初始化
        initializeByTemplate();
    }

    /**
     * @param title 表格标题，传“空值”，表示无标题
     * @param cls   实体对象，通过annotation.ExportField获取标题
     * @Title
     * @Description 构造函数
     */
    public CcpExcelReport(String title, Class<?> cls) {
        this(title, cls, 1);
    }

    /**
     * @param title  表格标题，传“空值”，表示无标题
     * @param cls    实体对象，通过annotation.ExportField获取标题
     * @param type   导出类型（1:导出数据；2：导出模板）
     * @param groups 导入分组
     * @Title CcpExcelReport
     * @Description 构造函数
     */
    public CcpExcelReport(String title, Class<?> cls, int type, int... groups) {
        // 初始化注解列表
        List<String> headerList = initAnnotationList(cls, type, groups);
        initialize(title, headerList);
    }

    /**
     * @param title   表格标题，传“空值”，表示无标题
     * @param headers 表头数组
     * @Title CcpExcelReport
     * @Description 构造函数
     */
    public CcpExcelReport(String title, String[] headers) {
        initialize(title, Arrays.asList(headers));
    }

    /**
     * @param title      表格标题，传“空值”，表示无标题
     * @param headerList 表头列表
     * @Title CcpExcelReport
     * @Description 构造函数
     */
    public CcpExcelReport(String title, List<String> headerList) {
        initialize(title, headerList);
    }

    /**
     * @param cls    实体对象，通过annotation.ExportField获取标题
     * @param type   导出类型（1:导出数据；2：导出模板）
     * @param groups 导入分组
     * @return List<String>
     * @Title initAnnotationList
     * @Description 根据实体类注解初始化表格注解
     */
    private List<String> initAnnotationList(Class<?> cls, int type, int... groups) {
        // Get annotation field
        Field[] fs = cls.getDeclaredFields();
        for (Field f : fs) {
            CcpExcelField ef = f.getAnnotation(CcpExcelField.class);
            if (ef != null && (ef.type() == 0 || ef.type() == type)) {
                if (groups != null && groups.length > 0) {
                    boolean inGroup = false;
                    for (int g : groups) {
                        if (inGroup) {
                            break;
                        }
                        for (int efg : ef.groups()) {
                            if (g == efg) {
                                inGroup = true;
                                annotationList.add(new Object[]{ef, f});
                                break;
                            }
                        }
                    }
                } else {
                    annotationList.add(new Object[]{ef, f});
                }
            }
        }
        // Get annotation method
        Method[] ms = cls.getDeclaredMethods();
        for (Method m : ms) {
            CcpExcelField ef = m.getAnnotation(CcpExcelField.class);
            if (ef != null && (ef.type() == 0 || ef.type() == type)) {
                if (groups != null && groups.length > 0) {
                    boolean inGroup = false;
                    for (int g : groups) {
                        if (inGroup) {
                            break;
                        }
                        for (int efg : ef.groups()) {
                            if (g == efg) {
                                inGroup = true;
                                annotationList.add(new Object[]{ef, m});
                                break;
                            }
                        }
                    }
                } else {
                    annotationList.add(new Object[]{ef, m});
                }
            }
        }
        // Field sorting
        Collections.sort(annotationList, new Comparator<Object[]>() {
            public int compare(Object[] o1, Object[] o2) {
                return new Integer(((CcpExcelField) o1[0]).sort()).compareTo(new Integer(((CcpExcelField) o2[0]).sort()));
            }
        });
        // Initialize
        List<String> headerList = new ArrayList<String>();
        for (Object[] os : annotationList) {
            String t = ((CcpExcelField) os[0]).title();
            // 如果是导出，则去掉注释
            if (type == 1) {
                String[] ss = StringUtils.split(t, "**", 2);
                if (ss.length == 2) {
                    t = ss[0];
                }
            }
            headerList.add(t);
        }

        return headerList;
    }

    /**
     * @throws CcpException
     * @Title initializeByTemplate
     * @Description 根据模版文件执行初始化
     */
    public void initializeByTemplate()
            throws CcpException {
        try {
            // 实体类不为null才执行初始化注解列表
            if (tempEntityClass != null) {
                // 初始化注解列表
                initAnnotationList(tempEntityClass, 1);
            }

            File templateFile = new File(templateFilePath);

            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(templateFile));

            // 读取excel模板
            this.hssfWorkbook = new HSSFWorkbook(fs);

            // 获取模版工作表，默认为excel的第一张（sheetNum=0）工作表
            this.hssfSheet = hssfWorkbook.getSheetAt(tempSheetNum < 0 ? 0 : tempSheetNum);

            // 置为使用模版
            this.templateUsed = true;

            // 设置模版行的行号
            this.tempStyleRownum = (tempStyleRownum < 0 ? 0 : tempStyleRownum);

            // 设置开始插数据的行号，不小于模版行的行号
            this.rownum = (firstDataRownum <= tempStyleRownum ? tempStyleRownum + 1 : firstDataRownum);

            logger.debug("Initialize By Template :[{}] success.", templateFilePath);
        } catch (Exception e) {
            throw new CcpException(ErrorCodeEnum.ERROR_EXCEL_REPORT_FAIL, e);
        }
    }

    /**
     * @param title      表格标题，传“空值”，表示无标题
     * @param headerList 表头列表
     * @Title initialize
     * @Description 初始化函数
     */
    private void initialize(String title, List<String> headerList) {
        this.hssfWorkbook = new HSSFWorkbook();

        // this.hssfWorkbook = new SXSSFWorkbook(500);
        this.hssfSheet = hssfWorkbook.createSheet("Export");
        this.stylesMap = createStyles(hssfWorkbook);
        // Create title
        if (StringUtils.isNotBlank(title)) {
            Row titleRow = hssfSheet.createRow(rownum++);
            titleRow.setHeightInPoints(30);
            Cell titleCell = titleRow.createCell(0);
            titleCell.setCellStyle(stylesMap.get("title"));
            titleCell.setCellValue(title);
            hssfSheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(),
                    titleRow.getRowNum(), headerList.size() - 1));
        }
        // Create header
        if (headerList == null) {
            throw new RuntimeException("headerList not null!");
        }
        Row headerRow = hssfSheet.createRow(rownum++);
        headerRow.setHeightInPoints(16);
        for (int i = 0; i < headerList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellStyle(stylesMap.get("header"));
            String[] ss = StringUtils.split(headerList.get(i), "**", 2);
            if (ss.length == 2) {
                cell.setCellValue(ss[0]);
                Comment comment = this.hssfSheet.createDrawingPatriarch()
                        .createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
                comment.setString(new XSSFRichTextString(ss[1]));
                cell.setCellComment(comment);
            } else {
                cell.setCellValue(headerList.get(i));
            }
            hssfSheet.autoSizeColumn(i);
        }
        for (int i = 0; i < headerList.size(); i++) {
            int colWidth = hssfSheet.getColumnWidth(i) * 2;
            hssfSheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
        }

        logger.debug("Initialize success.");
    }

    /**
     * @param wb 工作薄对象
     * @return 样式列表
     * @Description 创建表格样式
     */
    private Map<String, CellStyle> createStyles(Workbook wb) {
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();

        CellStyle style = wb.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        Font titleFont = wb.createFont();
        titleFont.setFontName("Arial");
        titleFont.setFontHeightInPoints((short) 16);
        titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style.setFont(titleFont);
        styles.put("title", style);

        style = wb.createCellStyle();
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        Font dataFont = wb.createFont();
        dataFont.setFontName("Arial");
        dataFont.setFontHeightInPoints((short) 10);
        style.setFont(dataFont);
        styles.put("data", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(CellStyle.ALIGN_LEFT);
        styles.put("data1", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(CellStyle.ALIGN_CENTER);
        styles.put("data2", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(CellStyle.ALIGN_RIGHT);
        styles.put("data3", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        // style.setWrapText(true);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        Font headerFont = wb.createFont();
        headerFont.setFontName("Arial");
        headerFont.setFontHeightInPoints((short) 10);
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(headerFont);
        styles.put("header", style);

        return styles;
    }

    /**
     * @param delRownum              --删除行的行号
     * @param positionRemoveRequired --是否删除行的位置
     * @Title delRow
     * @Description 删除行
     */
    public void delRow(int delRownum, boolean positionRemoveRequired) {
        // 删除内容和位置
        if (positionRemoveRequired) {
            // 整体向上移动1行，达到删除行的效果
            hssfSheet.shiftRows(delRownum + 1, hssfSheet.getLastRowNum(), -1);
        } else {
            // 只删除内容
            hssfSheet.removeRow(hssfSheet.getRow(delRownum));
        }
    }

    /**
     * @Title addRow
     * @Description 添加一行
     */
    public Row addRow() {
        return hssfSheet.createRow(rownum++);
    }

    /**
     * @param row    添加的行
     * @param column 添加列号
     * @param val    添加值
     * @return 单元格对象
     * @Title addCell
     * @Description 添加一个单元格
     */
    public Cell addCell(Row row, int column, Object val) {
        return this.addCell(row, column, val, 0, Class.class);
    }

    /**
     * @param row    添加的行
     * @param column 添加列号
     * @param val    添加值
     * @param align  对齐方式（1：靠左；2：居中；3：靠右）
     * @Title addCell
     * @Description 添加一个单元格
     */
    public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType) {
        Cell cell = row.createCell(column);

        // 单元格样式
        CellStyle style = null;

        // 使用模版行的单元格样式
        if (this.templateUsed) {
            style = this.hssfSheet.getRow(this.tempStyleRownum).getCell(column).getCellStyle();
        } else {
            style = this.stylesMap.get("data" + (align >= 1 && align <= 3 ? align : ""));
        }

        try {
            if (val == null) {
                cell.setCellValue("");
            } else if (val instanceof String) {
                cell.setCellValue((String) val);
            } else if (val instanceof Integer) {
                cell.setCellValue((Integer) val);
            } else if (val instanceof Long) {
                cell.setCellValue((Long) val);
            } else if (val instanceof Double) {
                cell.setCellValue((Double) val);
            } else if (val instanceof Float) {
                cell.setCellValue((Float) val);
            } else if (val instanceof Date) {
                DataFormat format = hssfWorkbook.createDataFormat();

                style.setDataFormat(format.getFormat("yyyy-MM-dd"));

                cell.setCellValue((Date) val);
            } else {
                if (fieldType != Class.class) {
                    cell.setCellValue((String) fieldType.getMethod("setValue", Object.class).invoke(null, val));
                } else {
                    cell.setCellValue((String) Class
                            .forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
                                    "fieldtype." + val.getClass().getSimpleName() + "Type"))
                            .getMethod("setValue", Object.class)
                            .invoke(null, val));
                }
            }
        } catch (Exception ex) {
            logger.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString());

            cell.setCellValue(val.toString());
        }

        // 设置单元格样式
        cell.setCellStyle(style);

        return cell;
    }

    /**
     * @param list 数据列表
     * @return
     * @Title setDataList
     * @Description 添加数据（通过annotation.ExportField添加数据）
     */
    public <E> CcpExcelReport setDataList(List<E> list) {
        for (E e : list) {
            int colunm = 0;
            Row row = this.addRow();
            StringBuilder sb = new StringBuilder();
            for (Object[] os : annotationList) {
                CcpExcelField ef = (CcpExcelField) os[0];
                Object val = null;
                // Get entity value
                try {
                    if (StringUtils.isNotBlank(ef.value())) {
                        val = CcpExcelReflections.invokeGetter(e, ef.value());
                    } else {
                        if (os[1] instanceof Field) {
                            val = CcpExcelReflections.invokeGetter(e, ((Field) os[1]).getName());
                        } else if (os[1] instanceof Method) {
                            val = CcpExcelReflections
                                    .invokeMethod(e, ((Method) os[1]).getName(), new Class[]{}, new Object[]{});
                        }
                    }
                } catch (Exception ex) {
                    // Failure to ignore
                    logger.info(ex.toString());
                    val = "";
                }
                this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
                sb.append(val + ", ");
            }
            logger.debug("Write success: [" + row.getRowNum() + "] " + sb.toString());
        }
        return this;
    }

    /**
     * @param os 输出数据流
     * @return
     * @throws IOException
     * @Title write
     * @Description 输出数据流
     */
    public CcpExcelReport write(OutputStream os)
            throws IOException {
        // 使用了模版且删除模版行
        if (this.templateUsed && this.tempRowRemoveRequired) {
            // 删除模版行
            delRow(this.tempStyleRownum, true);
        }

        hssfWorkbook.write(os);
        return this;
    }

    /**
     * @param name 输出文件名
     * @return
     * @throws IOException
     * @Title writeFile
     * @Description 输出到文件
     */
    public CcpExcelReport writeFile(String name)
            throws IOException {
        FileOutputStream os = new FileOutputStream(name);
        this.write(os);
        return this;
    }

    /**
     * @param
     * @return
     * @throws IOException
     * @Title dispose
     * @Description 清理临时文件
     */
    public CcpExcelReport dispose()
            throws IOException {
        hssfWorkbook.close();
        return this;
    }

    public boolean isTemplateUsed() {
        return templateUsed;
    }

    public String getTemplateFilePath() {
        return templateFilePath;
    }

    public void setTemplateFilePath(String templateFilePath) {
        this.templateFilePath = templateFilePath;
    }

    public Class<?> getTempEntityClass() {
        return tempEntityClass;
    }

    public void setTempEntityClass(Class<?> tempEntityClass) {
        this.tempEntityClass = tempEntityClass;
    }

    public int getTempSheetNum() {
        return tempSheetNum;
    }

    public void setTempSheetNum(int tempSheetNum) {
        this.tempSheetNum = tempSheetNum;
    }

    public int getTempStyleRownum() {
        return tempStyleRownum;
    }

    public void setTempStyleRownum(int tempStyleRownum) {
        this.tempStyleRownum = tempStyleRownum;
    }

    public int getFirstDataRownum() {
        return firstDataRownum;
    }

    public void setFirstDataRownum(int firstDataRownum) {
        this.firstDataRownum = firstDataRownum;
    }

    public boolean isTempRowRemoveRequired() {
        return tempRowRemoveRequired;
    }

    public void setTempRowRemoveRequired(boolean tempRowRemoveRequired) {
        this.tempRowRemoveRequired = tempRowRemoveRequired;
    }
}
